package com.kang.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RabbitMQUtils {

    public static ConnectionFactory factory;

    static {
        //重量级资源  类加载时执行只执行一次
        //创建mq的连接工厂对象
        factory = new ConnectionFactory();
        //设置连接mq的主机
        factory.setHost("127.0.0.1");
        //设置端口号
        factory.setPort(5672);
        //设置连接哪个虚拟主机
        factory.setVirtualHost("/ems");
        //设置访问虚拟主机的用户名密码
        factory.setUsername("ems");
        factory.setPassword("123");
    }
    //定义提供连接对象的方法
    public static Connection getConnection() {
        try {

            //获取链接对象
            Connection connection = factory.newConnection();
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //释放资源方法
    public static void closeConnectionAndChanel(Channel channel, Connection conn) {
        try {
            if (channel != null) {
                channel.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
